package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.commons.exception.LyException;
import com.leyou.commons.utils.RegexUtils;
import com.leyou.commons.utils.ValidateCodeUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    public static  String key_prefix = "ly:user:code:";
    /**
     * 判断用户是否存在
     * @param data
     * @param type
     * @return
     */
    @Override
    public Boolean checkData(String data, Integer type) {
        if(type!=1 && type!=2 || StringUtils.isEmpty(data)){
        throw  new LyException(400,"请求参数传递有误");
        }
        String dataType = null;
        if(type==1){
            dataType = "username";
        }else {
            dataType ="phone";
        }
        return  query().eq(dataType,data).count()==1;
    }

    /**
     * 发送验证码
     * @param phone
     */
    @Override
    public void sendCode(String phone) {
        if(!RegexUtils.isPhone(phone)){
        throw new LyException(400,"请求参数有误");
        }
        //调用工具生成4位数的验证码
        String code = ValidateCodeUtils.generateValidateCode(4);
        //发送消息到mq
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        amqpTemplate.convertAndSend("leyou","verify",map);
        // 保存验证码到redis
        redisTemplate.opsForValue().set(key_prefix + phone, code, 5, TimeUnit.MINUTES);
    }

    @Override
    @Transactional
    public void register(User user, String code) {
        //确认验证码有效
        if(StringUtils.isEmpty(user.getPhone())||StringUtils.isEmpty(code)||!code.equals(redisTemplate.opsForValue().get(key_prefix+user.getPhone()))){
        throw new LyException(400,"验证码或者手机号有误");
        }
        //对密码加密
        String password = passwordEncoder.encode(user.getPassword());
        //保存注册信息
        user.setPassword(password);
        save(user);
    }

    /**
     * 根据用户名和密码查询
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserDTO queryUserByUserNameAndPassword(String username, String password) {
        //判断用户是否存在
        User user = getOne(new QueryWrapper<User>().eq("username", username));
        if(user==null){
            throw new LyException(400,"用户名或者密码错误");
        }
        //判断密码是否正确
        if(!passwordEncoder.matches(password, user.getPassword())){
            // 密码错误
            throw new LyException(400, "用户名或密码错误");
        }
        return new UserDTO(user);
    }

}
